package emulator.shell.commands;

import java.io.FileInputStream;
import java.io.FileNotFoundException;

import emulator.EmulatorException;
import emulator.shell.DebugShell;
import emulator.shell.ShellCommand;
import emulator.util.AddressRange;
import emulator.util.file.FileHelper;
import emulator.util.file.FileInfo;

public class Load implements ShellCommand {

	@Override
	public boolean execute(DebugShell shell, String[] arg)
			throws EmulatorException, FileNotFoundException {
		if (arg.length < 3)
		{
			shell.getOut().println("Missing argument!");
			printHelp(shell);
		}
		else if (arg[1].equalsIgnoreCase("symbols"))
		{
			shell.getAssembler().loadSymbols(new FileInputStream(arg[2]), arg[2]);
		}
		else if (arg[1].equalsIgnoreCase("code"))
		{
			String file_name = arg[2];
			int start_address = -1;
			int block_size = -1;
			int file_format = FileHelper.guessFileFormat(file_name);
			if (file_format != FileHelper.FILE_FORMAT_UNKNOWN)
			{
				FileInfo info = FileHelper.getFileInfo(file_name, file_format);
				if (info != null)
				{
					start_address = info.getStartAddress();
					block_size = info.getBlockSize();
				}
				if (arg.length > 3)
				{
					start_address = shell.parseAddress(arg[3]);
					if (arg.length > 4)
						block_size = AddressRange.addressFromString(arg[4]);
				}
				if (info != null)
				{
					info.getLoadStrategy().loadToMemory(file_name,
							shell.getMemoryBlock(),
							start_address,
							block_size);
				}
			}
			else
			{
				shell.getOut().println("Unknown file format!");
				printHelp(shell);
			}
		}
		else
			printHelp(shell);
			
		return false;
	}

	@Override
	public void printHelp(DebugShell shell) {
		shell.getOut().println("command syntax:");
		shell.getOut().println("load symbols <filename> - load debugger symbols");
		shell.getOut().println("load code <filename> [<start> [<length>]]");
		shell.getOut().println("						- load file to memory");
	}

}
